"""
认证相关API：登录、刷新令牌、登出等
"""
from fastapi import APIRouter, HTTPException, status, Request, Depends
from datetime import datetime
from models.m import AdminUser, OperationLog
from schemas.admin_schemas import (
    LoginRequest, LoginResponse, RefreshTokenRequest,
    ResponseModel, AdminUserResponse
)
from utils.jwt_utils import create_access_token, create_refresh_token, verify_token
from utils.password_utils import verify_password
from utils.auth_middleware import get_current_user


auth_router = APIRouter(prefix="/admin/auth", tags=["管理员认证"])


@auth_router.post("/login", response_model=ResponseModel, summary="管理员登录")
async def login(request: Request, login_data: LoginRequest):
    """
    管理员登录
    - 验证用户名密码
    - 返回access_token和refresh_token
    """
    # 查询用户
    user = await AdminUser.get_or_none(username=login_data.username)
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    # 验证密码
    if not verify_password(login_data.password, user.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    # 检查用户状态
    if user.status != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="用户已被禁用"
        )
    
    # 获取角色信息
    await user.fetch_related('role')
    
    # 生成Token
    token_data = {
        "user_id": user.id,
        "username": user.username,
        "role_code": user.role.code
    }
    
    access_token = create_access_token(token_data)
    refresh_token = create_refresh_token(token_data)
    
    # 更新最后登录信息
    user.last_login_time = datetime.now()
    user.last_login_ip = request.client.host
    await user.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=user.id,
        action="login",
        module="认证管理",
        description=f"用户 {user.username} 登录系统",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        status=1
    )
    
    # 返回响应
    return {
        "code": 200,
        "message": "登录成功",
        "data": {
            "access_token": access_token,
            "refresh_token": refresh_token,
            "token_type": "bearer",
            "user_info": {
                "id": user.id,
                "username": user.username,
                "real_name": user.real_name,
                "avatar": user.avatar,
                "role_id": user.role.id,
                "role_name": user.role.name,
                "role_code": user.role.code,
            }
        }
    }


@auth_router.post("/refresh", response_model=ResponseModel, summary="刷新Token")
async def refresh_token(refresh_data: RefreshTokenRequest):
    """
    使用refresh_token获取新的access_token
    """
    # 验证refresh_token
    payload = verify_token(refresh_data.refresh_token, token_type="refresh")
    
    user_id = payload.get("user_id")
    if not user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid refresh token"
        )
    
    # 验证用户是否存在
    user = await AdminUser.get_or_none(id=user_id)
    if not user or user.status != 1:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="User not found or disabled"
        )
    
    # 获取角色信息
    await user.fetch_related('role')
    
    # 生成新的access_token
    token_data = {
        "user_id": user.id,
        "username": user.username,
        "role_code": user.role.code
    }
    
    new_access_token = create_access_token(token_data)
    
    return {
        "code": 200,
        "message": "刷新成功",
        "data": {
            "access_token": new_access_token,
            "token_type": "bearer"
        }
    }


@auth_router.get("/userinfo", response_model=ResponseModel, summary="获取当前用户信息")
async def get_userinfo(current_user: AdminUser = Depends(get_current_user)):
    """
    获取当前登录用户的详细信息
    """
    if not current_user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated"
        )
    
    # 获取角色和资源信息
    await current_user.fetch_related('role__resources')
    role = current_user.role
    
    # 获取用户的菜单权限（仅type=1的菜单）
    menus = []
    if role:
        resources = await role.resources.filter(status=1, type=1).order_by('sort')
        
        # 构建树形菜单
        menu_dict = {}
        for res in resources:
            menu_dict[res.id] = {
                "id": res.id,
                "name": res.name,
                "code": res.code,
                "path": res.path,
                "icon": res.icon,
                "pid": res.pid_id,
                "children": []
            }
        
        # 组装父子关系
        for menu_id, menu in menu_dict.items():
            if menu["pid"] is None:
                menus.append(menu)
            else:
                parent = menu_dict.get(menu["pid"])
                if parent:
                    parent["children"].append(menu)
    
    # 获取所有权限代码
    permissions = []
    if role:
        all_resources = await role.resources.filter(status=1)
        permissions = [res.code for res in all_resources]
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "id": current_user.id,
            "username": current_user.username,
            "real_name": current_user.real_name,
            "email": current_user.email,
            "phone": current_user.phone,
            "avatar": current_user.avatar,
            "status": current_user.status,
            "role": {
                "id": role.id,
                "name": role.name,
                "code": role.code,
            } if role else None,
            "menus": menus,
            "permissions": permissions,
        }
    }


@auth_router.post("/logout", response_model=ResponseModel, summary="登出")
async def logout(request: Request, current_user: AdminUser = Depends(get_current_user)):
    """
    登出（前端清除Token即可，这里记录日志）
    """
    if current_user:
        # 记录操作日志
        await OperationLog.create(
            user_id=current_user.id,
            action="logout",
            module="认证管理",
            description=f"用户 {current_user.username} 登出系统",
            ip=request.client.host,
            user_agent=request.headers.get("user-agent"),
            status=1
        )
    
    return {
        "code": 200,
        "message": "登出成功",
        "data": None
    }

